<template>
  <template v-if="!item.meta?.hide">
    <!-- 没有子路由的情况 -->
    <template v-if="!hasChild">
      <el-menu-item :index="resolvePath(item.path)" :route="item">
        <template #title>
          <!-- <el-icon v-if="item.meta?.icon">
            <menu-icon :icon="item.meta.icon" />
          </el-icon> -->
          <span>{{ item.meta?.title }}</span>
        </template>
      </el-menu-item>
    </template>

    <!-- 有子路由但只有一个子路由且不总是显示 -->
    <template v-else-if="showOnlyOneChild && onlyOneChild">
      <el-menu-item
        :index="resolvePath(onlyOneChild.path)"
        :route="onlyOneChild"
      >
        <el-icon v-if="onlyOneChild.meta?.icon">
          <menu-icon :icon="onlyOneChild.meta.icon" />
        </el-icon>
        <template #title>
          <span>{{ onlyOneChild.meta?.title }}</span>
        </template>
      </el-menu-item>
    </template>

    <!-- 有多个子路由 -->
    <el-sub-menu v-else-if="hasChild" :index="resolvePath(item.path)">
      <template #title>
        <el-icon v-if="item.meta?.icon">
          <menu-icon :icon="item.meta.icon" />
        </el-icon>
        <span>{{ item.meta?.title }}</span>
      </template>

      <menu-item
        v-for="child in item.children"
        :key="child.path"
        :item="child"
        :base-path="resolvePath(child.path)"
      />
    </el-sub-menu>
  </template>
</template>

<script setup>
import { computed } from "vue";
import path from "path-browserify";
import MenuIcon from "./MenuIcon.vue";

const props = defineProps({
  item: {
    type: Object,
    required: true,
  },
  basePath: {
    type: String,
    default: "",
  },
});

// 是否有子路由
const hasChild = computed(() => {
  const children = props.item.children;
  return children && children.length > 0;
});

// 是否只显示一个子路由
const showOnlyOneChild = computed(() => {
  const children = props.item.children;
  if (!children || children.length !== 1) {
    return false;
  }

  const onlyOneChild = children[0];
  return (
    onlyOneChild && !onlyOneChild.meta?.hide && !onlyOneChild.meta?.alwaysShow
  );
});

// 唯一的子路由（添加空值检查）
const onlyOneChild = computed(() => {
  return props.item.children && props.item.children[0];
});

// 解析路径
const resolvePath = (routePath) => {
  if (!routePath) return props.basePath;

  if (routePath.startsWith("/")) {
    return routePath;
  }
  return path.resolve(props.basePath, routePath);
};
</script>
